<template>
  <div class="ele-body" id="operation">
    <el-card shadow="never" v-loading="loading">
      <div class="_card">
        <el-form
            class="_form"
            ref="form"
            :rules="rules"
            :model="form"
            label-width="100px">
          <el-collapse v-model="moduleCollapse">
            <el-collapse-item v-for="(module, index) in form.module" :key="index" :name="index">
              <div slot="title" class="collapse-title">
                <i v-if="index" class="el-icon-delete" style="color: #a5865f" @click.stop="delModule(index)"></i>
                {{ moduleMap[module.type] }}
              </div>
              <el-form-item label="模块：" required>
                <el-radio-group v-model="module.type" size="small">
                  <el-radio-button v-for="(typeLabel, type) in moduleMap" :label="type" :key="type">
                    {{ typeLabel }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="上报单位：" :rules="{required: true, message: '请选择上报单位', trigger: 'change'}" :prop="'module.'+index+'.organization_id'" required>
                <organization-select :model_type="module.type" v-model="module.organization_id"
                ></organization-select>
              </el-form-item>
              <el-form-item label="巡查分类：" :rules="{required: true, message: '请选择巡查分类', trigger: 'change'}" :prop="'module.'+index+'.exception_category'" required>
                <exception-category-select :type="module.type" :unit="module.organization_id"
                                           v-model="module.exception_category"
                ></exception-category-select>
              </el-form-item>
              <el-form-item label="审核员：">
                <verify-user-select v-model="module.verify_user_list" :unit="module.organization_id"></verify-user-select>
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
          <div class="add-module">
            <el-button size="mini" icon="el-icon-plus" style="width: 100%;" @click="addModule">添加模块</el-button>
          </div>
          <el-form-item label="打标地址：" prop="address" required>
            <el-cascader
                clearable
                :disabled="!!form.id"
                v-model="form.area_id"
                class="ele-fluid"
                placeholder="请选择省市区"
                :options="regions"
                popper-class="ele-pop-wrap-higher"
                @change="changeArea"
            />
            <el-input
                v-model="form.address"
                :rows="2"
                type="textarea"
                placeholder="请在地图上选择详细地址"
            ></el-input>
<!--            <el-button size="mini" style="width: 100%; margin-top: 4px" @click="goHistory">查看历史标记记录</el-button>-->
          </el-form-item>
          <el-form-item label="标记类别：" prop="operation_category" required>
            <operation-category-select v-model="form.operation_category"></operation-category-select>
          </el-form-item>
          <el-form-item label="单位可见：">
            <el-select
                clearable
                v-model="form.organization_show"
                placeholder="请选择单位是否可见"
                class="ele-fluid"
            >
              <el-option label="可见" :value="1"/>
              <el-option label="不可见" :value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item v-show="form.operation_category !== 2" label="是否处罚：">
            <el-select
                clearable
                v-model="form.penalty"
                placeholder="请选择是否处罚"
                class="ele-fluid"
            >
              <el-option label="是" :value="1"/>
              <el-option label="否" :value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item label="巡飞次数:">
            <el-input clearable v-model="form.loitering_times" placeholder="请输入巡飞次数" />
          </el-form-item>
          <el-form-item label="巡飞时长:">
            <el-input clearable v-model="form.loitering_duration" placeholder="请输入巡飞时长" />
          </el-form-item>
          <el-form-item label="巡飞距离:">
            <el-input clearable v-model="form.loitering_distance" placeholder="请输入巡飞距离" />
          </el-form-item>
          <el-form-item label="备注:">
            <el-input
                :rows="3"
                clearable
                type="textarea"
                :maxlength="200"
                v-model="form.description"
                placeholder="备注"
            />
          </el-form-item>
          <el-form-item label="异常图片:">
            <upload-image :limit="99" multiple v-model="form.images"></upload-image>
          </el-form-item>
          <el-form-item v-if="moduleExists('illegal')">
            <el-button :loading="compareLoading" @click="compareNow">立即对比</el-button>
            <el-button @click="adjustDifference">调整差异</el-button>
          </el-form-item>
          <el-form-item>
            <el-button :loading="saveLoading" type="primary" @click="save">确认打标</el-button>
          </el-form-item>
        </el-form>
        <div style="width: calc(100% - 420px); padding: 0 12px">
          <MapMarkerContainer
              ref="map"
              :icon="form.operation_category"
              :data="list"
              :info-window-index="mapInfoWindowIndex"
              @marker="mapMarker"
              @markerClick="mapMarkerClick" />
        </div>

        <!-- 调整差异的弹窗 -->
        <div v-if="showAdjustModal">
          <adjust-difference :visible.sync="showAdjustModal" title="调整差异" :images="form.images" @callback="handleImagesChange" :markers="form.diff_points"/>
        </div>

      </div>
    </el-card>
  </div>
</template>

<script>
import uploadImage from '@/components/uploadImage'
import organizationSelect from '@/components/organizationSelect'
import exceptionCategorySelect from './components/exceptionCategorySelect'
import operationCategorySelect from './components/operationCategorySelect'
import verifyUserSelect from './components/verifyUserSelect.vue'
import MapMarkerContainer from '@/components/Map/MapMarkerContainer'
import { regionData } from 'element-china-area-data'
import AdjustDifference from './adjust-difference'

export default {
  name: 'operationEdit',
  components: {
    uploadImage,
    organizationSelect,
    exceptionCategorySelect,
    operationCategorySelect,
    verifyUserSelect,
    MapMarkerContainer,
    AdjustDifference
  },
  data() {
    return {
      type: '',
      regions: regionData,
      loading: false,
      saveLoading: false,
      list: [],
      moduleMap: {
        emergency: '应急',
        protection: '环保',
        illegal: '违建',
        way: '道路交通'
      },
      moduleCollapse: [0],
      form: {
        module: [
          {
            type: 'emergency',
            organization_id: null,
            exception_category: null,
            verify_user_list: []
          }
        ],
        operation_category: 2,
        area_id: [],
        address: '',
        organization_show: 1,
        penalty: 0,
        description: '',
        loitering_times: '',
        loitering_duration: '',
        loitering_distance: '',
        longitude: '',
        latitude: '',
        images: [],
        diff_points:[]
      },
      formReset: null,
      formCache: null,
      rules: {
        operation_category: [
          {required: true, message: '请选择标记类别', trigger: 'change'}
        ],
        address: [
          {required: true, message: '请选择打标地址', trigger: 'change'}
        ]
      },
      showAdjustModal: false,
      compareLoading:false,
      mapInfoWindowIndex: 0
    }
  },
  computed: {
    address : function() {
      return this.form.address
    }
  },
  watch: {
    form: {
      handler(val){
        if (val && val.id === 0) {
          this.formCache = JSON.parse(JSON.stringify(this.form))
        }
      },
      deep: true
    },

    address: {
      handler: function (val) {
        if(val && ! this.form.id && this.type === 'illegal'){
          this.getLastImageByAddress()
        }
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (vm.$refs.map) {
        vm.$refs.map.removeMarker()
      }
    })
  },
  beforeRouteLeave(to, from, next) {
    this.form = JSON.parse(JSON.stringify(this.formReset))
    this.$refs['form'].resetFields()
    next()
  },
  methods: {
    addModule() {
      let module = this.form.module
      const existsModules = module.reduce((result, item) => {
        return result.concat(item['type'])
      }, [])
      const usableModules = Object.keys(this.moduleMap).filter(key => !existsModules.includes(key))
      module.push({
        type: usableModules.length ? usableModules[0] : 'emergency',
        organization_id: null,
        exception_category: null,
        verify_user_list: []
      })
      this.$set(this.form, 'module', module)
      this.moduleCollapse = [module.length - 1]
    },
    delModule(index) {
      let module = this.form.module
      module.splice(index, 1)
      this.$set(this.form, 'module', module)
    },
    moduleExists(module) {
      const existsModules = this.form.module.reduce((result, item) => {
        return result.concat(item['type'])
      }, [])

      return existsModules.indexOf(module) !== -1
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.saveLoading = true
          this.$http
              .post('/operation/add', this.form)
              .then((res) => {
                this.saveLoading = false
                if (res.data.code === 0) {
                  this.$alert('成功打标' +res.data.data+ '个', '打标成功', {
                    confirmButtonText: '确定',
                    callback() {
                      this.$router.go(0)
                    }
                  })
                } else {
                  this.$message.error(res.data.msg)
                }
              })
              .catch((e) => {
                this.saveLoading = false
                this.$message.error(e.message)
              })
        } else {
          return false
        }
      })
    },
    mapMarker({event, address}) {
      this.form.id = 0
      this.form.images = []
      this.form.description = ''
      this.form.area_id = [address.adcode.substring(0, 2), address.adcode.substring(0, 4), address.adcode]
      this.form.address = address.township + address.street + address.streetNumber
      this.form.longitude = event.lnglat.lng
      this.form.latitude = event.lnglat.lat
    },
    mapMarkerClick(index) {
      if (typeof this.list[index] == 'undefined') {
        this.form = JSON.parse(JSON.stringify(this.formCache))
      } else {
        this.mapInfoWindowIndex = index
        this.form = JSON.parse(JSON.stringify(this.list[index]))
      }
    },
    goHistory() {
      if (this.form.address) {
        let query = {
          addr: JSON.stringify({
            lnglat: this.form.lnglat,
            address: this.form.address
          })
        }
        this.$router.push({
          path: '/operation/history/' + this.type,
          query: query
        })
      } else {
        this.$router.push('/operation/history/' + this.type)
      }
    },
    changeArea(val) {
      this.form.address = ''
      const getLabel = function (val, arr, index = 0, res = []) {
        for (let i in arr) {
          if (arr[i].value === val[index]) {
            res.push(arr[i].label)
            if (index === val.length - 1) {
              return res
            } else {
              return getLabel(val, arr[i].children, ++index, res)
            }
          }
        }
      }
      let city = getLabel(val, this.regions)
      this.$refs.map.setCenterByAddress(city.join())
    },

    /* 调整差异 add 202309152231 */
    adjustDifference() {
      console.log('adjustDifference',this.form.id)
      if(this.form.images.length > 1){
        this.showAdjustModal = true;
      }
      else{
        this.$message({
          showClose: true,
          message: '低于2张图片无法调整差异',
          type: 'error'
        });
      }

    },

    /* 立即比对 add 202309152234*/
    compareNow() {
      if(this.form.images.length > 1){
        console.log('compareNow',this.form.id)
        this.compareLoading = true
        this.$http
          .post('/illegal/compareImg', this.form)
          .then((res) => {
            this.compareLoading = false
            if (res.data.code === 0) {
              this.$message({ type: 'success', message: res.data.msg })
              this.handleImagesChange(res.data.data.url)
              this.form.diff_points = res.data.data.points
            } else {
              this.$message.error(res.data.msg)
              this.compareLoading = false
            }
          })
          .catch((e) => {
            this.compareLoading = false
            this.$message.error(e.message)
          })
      }
      else{
        this.$message({
          showClose: true,
          message: '无法进行图片比对',
          type: 'error'
        });
      }

    },
    /* 更新图片显示 add 202309160935*/
    handleImagesChange(val) {
      console.log(val)
      if(this.form.images.length == 2){
        this.form.images.push(val)
      }

      if(this.form.images.length == 3){
        this.form.images.splice(2,1,val)
      }

    },
    /* 通过地址获取上一次的图片*/
    getLastImageByAddress() {
      this.$http
        .post('/illegal/getLastImageByAddress', {address: this.address})
        .then((res) => {
          if (res.data.code === 0) {
            this.form.images = []
            this.form.images.unshift(res.data.data.url)
          }else{
            this.form.images = []
          }
        })
        .catch((e) => {
          this.$message.error(e.message)
        })
    },
  }
}
</script>

<style scoped>
._card {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
}

._form {
  width: 400px;
  max-height: 700px;
  overflow-y: auto;
}

.add-module {
  padding: 0;
  margin: 6px 0;
}

.collapse-title {
  padding-left: 6px;
  i {
    margin-right: 6px;
  }
}
</style>
<style>
#operation .el-collapse-item__header {
  background-color: rgba(0, 0, 0, 0)
}
#operation .el-collapse-item__wrap {
  background-color: rgba(0, 0, 0, 0)
}
#operation .el-collapse-item__content {
  padding-bottom: 0 !important;
}
</style>